package com.dingdang.controller;

import com.dingdang.data.Result;
import com.dingdang.em.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("admin")
@Api(value = "后台登录")
public class TbAdminController {

    @PostMapping("login")
    @ApiOperation(value = "账号密码登录")
    @ApiImplicitParam(name = "username",value = "后台登录的名称",required = true,paramType = "query")
    public Result login(@RequestParam("username") String username,@RequestParam("password")String password) {
        //整合shiro
        //获取suject对象
        Subject subject = SecurityUtils.getSubject();
        //2, 将传来的账号密码 包装成 shiro 的 token 对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3, 调用subject的login方法,执行登录逻辑
        try {
            subject.login(token);
        } catch (UnknownAccountException e1) {
            //该用户账号不存在
            return Result.response(ResultEnum.USER_NO);
        } catch (IncorrectCredentialsException e2) {
            //用户或者密码错误
            return Result.response(ResultEnum.PASSWORD_ERROR);
        }
        return Result.response(ResultEnum.SUCCESS).setData(token);
    }
}
